package com.sc.nft.util;

import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author liGen
 * @version 1.0
 * @date 2023/12/5 14:51
 */
public class Beans {

    public Beans() {
    }

    public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
        BeanUtils.copyProperties(source, target, ignoreProperties);
    }

    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullProperties(source));
    }

    public static void copyPropertiesIgnoreNull(Object source, Object target, String... ignoreProperties) {
        String[] nullProperties = getNullProperties(source);
        List<String> list = Lists.newArrayList(nullProperties);
        String[] all = ignoreProperties;
        int var6 = ignoreProperties.length;

        for (int var7 = 0; var7 < var6; ++var7) {
            String p = all[var7];
            if (!list.contains(p)) {
                list.add(p);
            }
        }

        all = new String[list.size()];
        BeanUtils.copyProperties(source, target, (String[]) list.toArray(all));
    }

    private static String[] getNullProperties(Object src) {
        BeanWrapper srcBean = new BeanWrapperImpl(src);
        PropertyDescriptor[] pds = srcBean.getPropertyDescriptors();
        Set<String> emptyName = new HashSet();
        PropertyDescriptor[] var4 = pds;
        int var5 = pds.length;

        for (int var6 = 0; var6 < var5; ++var6) {
            PropertyDescriptor p = var4[var6];
            Object srcValue = srcBean.getPropertyValue(p.getName());
            if (srcValue == null) {
                emptyName.add(p.getName());
            }
        }

        String[] result = new String[emptyName.size()];
        return (String[]) emptyName.toArray(result);
    }
}
